package com.haierCamera.customapplication.ui.main;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.api.vo.ConfigDeviceResponse;

import com.haierCamera.customapplication.databinding.HzklActivityDeviceNormalAddBinding;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.business.util.TaskPoolHelper;
import com.haierCamera.customapplication.ui.main.widget.DialogLinkDeviceWifiNotify;
import com.haierCamera.customapplication.ui.zxing.activity.CaptureActivity;
import com.haierCamera.customapplication.utils.ResourceConvertUtils;
import com.haierCamera.customapplication.utils.SharedPreferencesUtils;
import com.haierCamera.customapplication.utils.StringUtils;
import com.haierCamera.customapplication.utils.android.ActivityManager;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;
import com.haierCamera.customapplication.widget.CalProgressView;
import com.lechange.common.configwifi.LCSmartConfig;
import com.lechange.opensdk.api.bean.DeviceOnline;
import com.lechange.opensdk.configwifi.LCOpenSDK_ConfigWifi;
import com.lechange.opensdk.media.DeviceInitInfo;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import dagger.Lazy;

public class CameraDeviceAddActivity extends BaseActivity {

    HzklActivityDeviceNormalAddBinding binding;

    private static final String TAG = "LCOpenSDK-CameraDeviceAddActivity";
    private final int DEVICE_SEARCH_SUCCESS = 0x1B;
    private final int DEVICE_SEARCH_FAILED = 0x1C;
    private final int ON_LINE_SUCCESS = 0x11;

    private final int DEVICE_INIT_SUCCESS = 0x18;
    private final int DEVICE_INIT_FAILED = 0x19;
    private final int DEVICE_INIT_BY_IP_FAILED = 0x1A;

    private static final int CONFIG_WIFI_TIMEOUT_TIME = 60 * 1000;
    private static final int CONFIG_SEARCH_DEVICE_TIME = 60 * 1000;

    private final int INITMODE_UNICAST = 0;
    private final int INITMODE_MULTICAST = 1;
    private WifiInfo mWifiInfo;
    private String devType="";
    String ssid="";
    private int curInitMode = INITMODE_MULTICAST;
    private boolean isSecondInitByIP=false;

    private DeviceInitInfo deviceInitInfo = null;
    @Inject
    ApiService apiService;
    @Inject
    Lazy<HttpErrorProcess> errorProcessLazy;

    String key;
    DialogLinkDeviceWifiNotify dialogLink;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_device_normal_add);


//        binding.btnWireless.setOnClickListener((v)->{//无线
//            if (TextUtils.isEmpty(binding.edSn.getText().toString())) {
//                toast("序列号不能为空！");
//            } else {
//                List<String> split= Arrays.asList(SharedPreferencesUtils.getString("dt","").split(","));
//
//                boolean isGoSoft = false;
//                for (int i = 0; i < split.size(); i++) {
//                    if (getIntent().getStringExtra("dt")!=null && !getIntent().getStringExtra("dt").equals("") &&
//                            getIntent().getStringExtra("dt").equals(split.get(i)) ) {
//                        isGoSoft = true;
//                    }
//                }
//                if (isGoSoft) {
//                    startActivity(new Intent(CameraDeviceAddActivity.this,HZKLSoftAPAddActivity.class)
//                            .putExtra("sn",getIntent().getStringExtra("sn"))
//                            .putExtra("sc",getIntent().getStringExtra("sc"))
//                            .putExtra("dt",getIntent().getStringExtra("dt"))
//                            .putExtra("ssid",ssid)
//                            .putExtra("ssidPwd",binding.edWifiPsw.getText().toString()));
//
//                } else {
//                    requestStoragePermission();
//                }
//            }
//        });
//
//        binding.btnWired.setOnClickListener((v)->{//有线
//            if (TextUtils.isEmpty(binding.edSn.getText().toString())) {
//                toast( "序列号不能为空！");
//            } else {
//                checkOnBindandline();
//            }
//        });
//
//        binding.imgReturn.setOnClickListener((v)->{
//            finish();
//        });
//
//        WifiManager mWifiManager = (WifiManager) getApplicationContext().getSystemService(Activity.WIFI_SERVICE);
//        mWifiInfo = mWifiManager.getConnectionInfo();
//        if (mWifiInfo != null) {
//            ssid=mWifiInfo.getSSID();
//            ssid = ssid.substring(1,ssid.length()-1);
//        }
//        binding.edWifi.setText(ssid+"");
//
//        binding.edSn.setText(getIntent().getStringExtra("sn"));
//        binding.edSecurity.setText(getIntent().getStringExtra("sc"));
////        Business.getInstance().unBindDevice(getIntent().getStringExtra("sn"),new Handler());
//        if (SharedPreferencesUtils.getString("dt","").equals("")
//                || SharedPreferencesUtils.getString("dt","") == null) {
//            SharedPreferencesUtils.saveString("dt", "TP7S,TP7SE,TP1D,TE3");
//        }
//        configDevice();
        showWifiConfig();

        binding.btnRetry.setOnClickListener((v)->{
            binding.layoutRetry.setVisibility(View.GONE);
            binding.customPro.setVisibility(View.VISIBLE);
            binding.queryLoad.setVisibility(View.VISIBLE);
            showWifiConfig();
        });
        binding.btnQuit.setOnClickListener((v)->{
            if (ActivityManager.getInstance().getActivity(HZKLCameraDeviceAddStepOneActivity.class)!=null) {
                ActivityManager.getInstance().getActivity(HZKLCameraDeviceAddStepOneActivity.class).finish();
            }
            if (ActivityManager.getInstance().getActivity(HZKLCameraDeviceAddStepTwoActivity.class)!=null) {
                ActivityManager.getInstance().getActivity(HZKLCameraDeviceAddStepTwoActivity.class).finish();
            }
            if (ActivityManager.getInstance().getActivity(HZKLCameraDeviceAddStepThreeActivity.class)!=null) {
                ActivityManager.getInstance().getActivity(HZKLCameraDeviceAddStepThreeActivity.class).finish();
            }

            finish();
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("TAG", "msg.what  " + msg.what);
            switch (msg.what) {
                case DEVICE_INIT_SUCCESS:
                    Log.i("TAG","DEVICE_INIT_SUCCESS-sc:" + msg.obj.toString());
                    binding.queryLoad.setStop();
//                    binding.probar.setVisibility(View.GONE);

                    Intent intent = new Intent(CameraDeviceAddActivity.this, InitDeviceActivity.class);
                    intent.putExtra("devSc", msg.obj.toString());//携带设备SC码
                    intent.putExtra("devId", getIntent().getStringExtra("sn"));
                    intent.putExtra("DeviceInitInfo", deviceInitInfo);
                    startActivityForResult(intent,10000);
                    finish();

                    break;
                case DEVICE_INIT_FAILED:
                    //组播失败后走单播
                    if(curInitMode==INITMODE_UNICAST){
//                        toast("deviceInitFailed: " + (String) msg.obj);
                        toast("初始化信息失败");
                        binding.queryLoad.setStop();
//                        binding.probar.setVisibility(View.GONE);
                        finish();
                        return;
                    }
                    curInitMode = INITMODE_UNICAST;
                    if (null != deviceInitInfo) {
                        initDevice(deviceInitInfo, curInitMode,getIntent().getStringExtra("sn"));
                    }

                    break;
                case DEVICE_INIT_BY_IP_FAILED:
                    if (isSecondInitByIP) {
                        curInitMode=INITMODE_MULTICAST;
                        isSecondInitByIP=false;
//                        toast("deviceInitByIPFailed: " + (String) msg.obj);
//                        mProgressDialog.setStop();
                        binding.queryLoad.setStop();
//                        binding.probar.setVisibility(View.GONE);
                        showTipDialog(getResources().getString(R.string.HZKLtoast_device_init_device_failed));
                        return;
                    }
                    if (null != deviceInitInfo) {
                        isSecondInitByIP=true;
                        initDevice(deviceInitInfo, curInitMode,getIntent().getStringExtra("sn"));
                    }
                    curInitMode = INITMODE_MULTICAST;
                    break;
                case DEVICE_SEARCH_SUCCESS:
                    Log.d(TAG, "deviceSearchSuccess");
                    stopConfig();
                    binding.queryLoad.setStop();
//                    binding.probar.setVisibility(View.GONE);
                    deviceInitInfo = (DeviceInitInfo) msg.obj;
                    if(getIntent().getStringExtra("sc") != null
                            && getIntent().getStringExtra("sc").length() == 8) {
//                        Log.e(TAG, " SC_initDevice, devSc : " + devSc);
//                        mProgressDialog.setStart(getResources().getString(R.string.HZKLchecking_device_online));
//                        checkOnline();
                        binding.queryLoad.setStop();
//                        binding.probar.setVisibility(View.GONE);
                        Intent intent2 = new Intent(CameraDeviceAddActivity.this, InitDeviceActivity.class);
                        intent2.putExtra("devSc", getIntent().getStringExtra("sc"));//携带设备SC码
                        intent2.putExtra("devId", getIntent().getStringExtra("sn"));
                        intent2.putExtra("DeviceInitInfo", deviceInitInfo);
                        startActivityForResult(intent2,10000);
                        finish();
                    }else {//SC码小于8位走原来流程
                        if (null != msg.obj) {
                            Log.d(TAG, "initDevice");
                            binding.queryLoad.setStart(getResources().getString(R.string.HZKLinit_devices));
//                            binding.tvIntro.setText(getResources().getString(R.string.HZKLinit_devices));
                            initDevice((DeviceInitInfo) msg.obj, curInitMode,getIntent().getStringExtra("sn"));
                        }
                    }
//                    Intent intent = new Intent(CameraDeviceAddActivity.this, InitDeviceActivity.class);
//                    intent.putExtra("devSc", binding.edSecurity.getText().toString());//携带设备SC码
//                    intent.putExtra("devId", binding.edSn.getText().toString());
//                    intent.putExtra("DeviceInitInfo", (Serializable) msg.obj);
//                    startActivityForResult(intent,10000);
//                    finish();

                    break;
                case DEVICE_SEARCH_FAILED:
                    stopConfig();
                    binding.queryLoad.setStop();
//                    binding.probar.setVisibility(View.GONE);
//                    toast("deviceSearchFailed:" + msg.obj);
                    toast("搜索设备初始化信息失败");
//                    finish();
                    binding.customPro.setVisibility(View.GONE);
                    binding.queryLoad.setVisibility(View.GONE);
                    binding.layoutRetry.setVisibility(View.VISIBLE);
                    break;
                case ON_LINE_SUCCESS:
                    //设备在线
                    Log.d(TAG,"check_online_success");
                    if(getIntent().getStringExtra("sc") != null
                            && getIntent().getStringExtra("sc").length() == 8){
                        key = getIntent().getStringExtra("sc");
//                        bindDevice();
                        addByService(getIntent().getStringExtra("sn"),key);
                    }else{
                        key = getIntent().getStringExtra("sc");
                        unBindDeviceInfo();
                    }
//                    binding.tvIntro.setText(getResources().getString(R.string.HZKLbinding_device));
                    binding.queryLoad.setStart(getResources().getString(R.string.HZKLbinding_device));//绑定设备中
//                    binding.probar.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopConfig();
    }

    /**
     * 无线配对校验
     */
//    public void checkOnBindAndRemind() {
//        Business.getInstance().checkBindOrNot(binding.edSn.getText().toString(),
//                new Handler() {
//                    @Override
//                    public void handleMessage(Message msg) {
//                        // TODO Auto-generated method stub
//                        super.handleMessage(msg);
//                        Business.RetObject retObject = (Business.RetObject) msg.obj;
//                        if (msg.what == 0) {
//                            CheckDeviceBindOrNot.Response resp = (CheckDeviceBindOrNot.Response) retObject.resp;
//                            if (!resp.data.isBind) {
//                                showWifiConfig();
//                            } else if (resp.data.isBind && resp.data.isMine)
//                                toast(getString(R.string.HZKLtoast_adddevice_already_binded_by_self));
//                            else
//                                toast(getString(R.string.HZKLtoast_adddevice_already_binded_by_others));
//                        } else {
//                            Log.i("TAG","checkOnBindAndRemind-" + retObject.mMsg);
//                            toast(retObject.mMsg);
//                        }
//                    }
//                });
//    }
//
//
//    /**
//     * 有线配对校验
//     */
//    private void checkOnBindandline() {
//        Business.getInstance().checkBindOrNot(binding.edSn.getText().toString(),
//                new Handler() {
//                    @Override
//                    public void handleMessage(Message msg) {
//                        // TODO Auto-generated method stub
//                        super.handleMessage(msg);
//                        Business.RetObject retObject = (Business.RetObject) msg.obj;
//                        if (msg.what == 0) {
//                            CheckDeviceBindOrNot.Response resp = (CheckDeviceBindOrNot.Response) retObject.resp;
//                            if (!resp.data.isBind) {
//                                binding.queryLoad.setStart(getString(R.string.HZKLsearch_devices)) ;
//                                binding.probar.setVisibility(View.VISIBLE);
//                                searchDevice(CONFIG_SEARCH_DEVICE_TIME);
//                            } else if (resp.data.isBind && resp.data.isMine)
//                                toast(getString(R.string.HZKLtoast_adddevice_already_binded_by_self));
//                            else
//                                toast(getString(R.string.HZKLtoast_adddevice_already_binded_by_others));
//                        } else {
//                            toast(retObject.mMsg);
//                        }
//                    }
//                });
//    }

    /**
     * 开启无线配网流程（权限检查，配对说明）
     */
    public void showWifiConfig() {
        boolean isMinSDKM = Build.VERSION.SDK_INT < 23;
        boolean isGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        if (isMinSDKM || isGranted) {

            startConfig();
            // 开启无线配对
            return;
        }

        requestLocationPermission();
    }

    /**
     * 校验在线
     */
//    private void checkOnline() {
//        Business.getInstance().checkOnline(binding.edSn.getText().toString(),
//                new Handler() {
//                    @Override
//                    public void handleMessage(Message msg) {
//                        Business.RetObject retObject = (Business.RetObject) msg.obj;
//                        switch (msg.what) {
//                            case 0:
//                                if (((DeviceOnline.Response) retObject.resp).data.onLine.equals("1")) {
//                                    toast("Online");
//
//                                    mHandler.obtainMessage(ON_LINE_SUCCESS).sendToTarget();
////                                    addByService(binding.edSn.getText().toString()
////                                            ,binding.edSecurity.getText().toString());
//                                } else {
////                                    showPairDescription();
//                                    startConfig();
//                                }
//                                break;
//                            case -1000:
//                                Log.e(TAG,"check_online_respond : -1000");
////                                mHandler.obtainMessage(ON_LINE_FAILED).sendToTarget();
//                                break;
//                            default:
//                                Log.e(TAG,"checkonline  :  "+msg.what);
////                                mHandler.obtainMessage(ON_LINE_FAILED).sendToTarget();
//                                break;
//                        }
//                    }
//                });
//
//    }

    public void initDevice(final DeviceInitInfo deviceInitInfo, int initMode,String devId) {
        //1.使用组播进行初始化（initMode=INITMODE_MULTICAST）,走else流程
        //2.组播失败后再使用单播（initMode=INITMODE_UNICAST），此时直接使用组播时输入的秘钥进行初始化
        if (initMode == INITMODE_UNICAST) {
            Log.i("TAG","initDevice-INITMODE_UNICAST");
            Business.getInstance().initDeviceByIP(deviceInitInfo.mMac, deviceInitInfo.mIp, key, new Handler() {
                public void handleMessage(Message msg) {
                    String message = (String) msg.obj;
                    if (msg.what == 0) {
                        mHandler.obtainMessage(DEVICE_INIT_SUCCESS, key).sendToTarget();
                    } else {
                        mHandler.obtainMessage(DEVICE_INIT_BY_IP_FAILED, message).sendToTarget();
                    }
                }
            });
        } else {
            Log.i("TAG","initDevice-INITMODE_MULTICAST");
            final EditText et = new EditText(this);
            et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(32)});//20
            final String deviceId = devId;

            final int status = deviceInitInfo.mStatus;

            //not support init
            if (status == 0 && !Business.getInstance().isOversea) {
                key = "";
                Log.i("TAG","inner, go bind without key");
                mHandler.obtainMessage(DEVICE_INIT_SUCCESS, key).sendToTarget();

            } else {
                if (status == 1) {
                    et.setHint(getString(R.string.HZKLtoast_adddevice_input_device_key_to_init));
                } else {
                    et.setHint(getString(R.string.HZKLtoast_adddevice_input_device_key_after_init));//输入设备初始化后的设备密码
                }

                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setTitle("设置您的设备密码")
                        .setMessage("1. 8-32位数字、字母、符号组合（区分大小写）\n" +
                                "2. 设备密码旨在更好地保障您设备的信息安全，请妥善保管\n" +
                                "3. 如您遗忘密码，可将设备恢复默认配置，重新添加，设置新的设备密码")
                        .setView(et)
                        .setPositiveButton(R.string.HZKLdialog_positive,
                                new android.content.DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        key = et.getText().toString();
                                        if (!StringUtils.isTest(key)) {
                                            toast("设备密码不符合格式");
                                            return;
                                        }
                                        Log.i("TAG","status-" + status);
                                        if (status == 0 || status == 2) {
                                            if (Business.getInstance().isOversea)
                                                checkPwdValidity(deviceId, deviceInitInfo.mIp, deviceInitInfo.mPort, key, mHandler);
                                            else
                                                Log.i("TAG","inner, go bind with key");
                                                mHandler.obtainMessage(DEVICE_INIT_SUCCESS, "" + key).sendToTarget();
                                        } else if (status == 1) {
                                            Log.i("TAG","initDevice-" + deviceInitInfo.mMac + "/key-" + key);
                                            Business.getInstance().initDevice(deviceInitInfo.mMac, key, new Handler() {
                                                public void handleMessage(Message msg) {
                                                    String message = (String) msg.obj;
                                                    if (msg.what == 0) {
                                                        mHandler.obtainMessage(DEVICE_INIT_SUCCESS, key).sendToTarget();
                                                    } else {
                                                        mHandler.obtainMessage(DEVICE_INIT_FAILED, message).sendToTarget();
                                                    }
                                                }
                                            });
                                        }
                                    }
                                })
                        .setNegativeButton(R.string.HZKLdialog_nagative,
                                new android.content.DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mHandler.obtainMessage(DEVICE_INIT_FAILED, "Init has been cancelled").sendToTarget();
                                    }
                                })
                        .create();
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            }
        }
    }

    /****
     * 海外设备需要校验密码
     * @param deviceId
     * @param ip
     * @param port
     * @param key
     * @param handler
     */
    public void checkPwdValidity(final String deviceId, final String ip, final int port, final String key, final Handler handler) {
        TaskPoolHelper.addTask(new TaskPoolHelper.RunnableTask("real") {
            @Override
            public void run() {
                if (0 == Business.getInstance().checkPwdValidity(deviceId, ip, port, key)) {
                    Log.i("TAG","checkPwdValidity success");
                    handler.obtainMessage(DEVICE_INIT_SUCCESS, "" + key).sendToTarget();
                } else {
                    handler.obtainMessage(DEVICE_INIT_FAILED, "checkPwdValidity failed").sendToTarget();
                }
            }
        });
    }

    private void unBindDeviceInfo(){
        if(!Business.getInstance().isOversea){
            Business.getInstance().unBindDeviceInfo(getIntent().getStringExtra("sn"), new Handler(){
                public void handleMessage(Message msg) {
                    String message = (String) msg.obj;
                    Log.d("TAG", "unBindDeviceInfo,"+message);

                    if (msg.what == 0) {
                        if(message.contains("Auth")){
//                            bindDevice();
                            Log.i("TAG","addByService_1");
                            if (key.equals( getIntent().getStringExtra("sc"))) {
                                final EditText et = new EditText(CameraDeviceAddActivity.this);
                                final AlertDialog dialog = new AlertDialog.Builder(CameraDeviceAddActivity.this)
                                        .setTitle(R.string.HZKLalarm_message_keyinput_dialog_title)
                                        .setIcon(android.R.drawable.ic_dialog_info)
                                        .setView(et)
                                        .setPositiveButton(R.string.HZKLdialog_positive, null)
                                        .setNegativeButton(R.string.HZKLdialog_nagative, null)
                                        .create();
                                dialog.setCanceledOnTouchOutside(false);
                                dialog.show();

                                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                                    public void onClick(View v) {
                                        if (TextUtils.isEmpty(et.getText())) {
                                            toast("Input can't be empty");
                                            return;
                                        }
                                        key = et.getText().toString();
//                                    bindDevice();

                                        addByService(getIntent().getStringExtra("sn"), key);
                                        dialog.dismiss();
                                    }
                                });
                            }else {
                                addByService(getIntent().getStringExtra("sn"), key);
                            }

                        }
                        else if(message.contains("RegCode")){

                            addByService(getIntent().getStringExtra("sn"),getIntent().getStringExtra("sc"));
                        }
                        else{
                            Log.i("TAG","addByService_2");
                            key = "";
                            addByService(getIntent().getStringExtra("sn"),key);
//                            bindDevice();
                        }
                    } else {
                        toast("unBindDeviceInfo failed");
                        Log.d(TAG, message);
                    }
                }
            });
        }
        else{ //oversea
//            bindDevice();
            Log.i("TAG","addByService_3");
            addByService(getIntent().getStringExtra("sn"),key);
        }

    }

    private void addByService(String serialNumber, String securityCode){
        Log.i("TAG","CameraDeviceAddActivity_addByService-sn:" +serialNumber + "/sc:" + securityCode);
        ResourceConvertUtils.convertToResource(apiService.addAndBind(serialNumber,securityCode))
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            Log.i("TAG","ERROR--" +resource.errorCode+ "/" + resource.toString());
                            errorProcessLazy.get().process(resource);

                            binding.queryLoad.setStop();

                            binding.customPro.setVisibility(View.GONE);
                            binding.queryLoad.setVisibility(View.GONE);
                            binding.layoutRetry.setVisibility(View.VISIBLE);
//                            binding.probar.setVisibility(View.GONE);
                            break;
                        case SUCCESS:
                            Log.i("TAG","addCameraByServiceSuccess--");
                            toast("添加成功");

                            binding.queryLoad.setStop();
//                            binding.probar.setVisibility(View.GONE);

                            startActivityForResult(new Intent(this
                                            ,HZKLEditCameraNameActivity.class)
                                            .putExtra("name",resource.data.bindName)
                                            .putExtra("accountDeviceId",resource.data.accountDeviceId +"")
                                    ,10000);
                            finish();

                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    private void configDevice() {
        ResourceConvertUtils.convertToResource(apiService.configDevice())
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            errorProcessLazy.get().process(resource);
                            break;
                        case SUCCESS:
                            List<ConfigDeviceResponse.item> list =  resource.data;
                            List<String> list_s = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                list_s.add(list.get(i).value);
                            }
                            SharedPreferencesUtils.saveString("dt",StringUtils.listToString1(list_s));

                            break;
                        case LOADING:
                            break;

                    }
                });
    }
    /**
     * 显示配对说明
     */
//    private void showPairDescription() {
//
//        DialogInterface.OnClickListener dialogOnclicListener = new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                switch (which) {
//                    case Dialog.BUTTON_POSITIVE:
//                        startConfig();
//                        break;
//                    case Dialog.BUTTON_NEGATIVE:
//                        break;
//                    case Dialog.BUTTON_NEUTRAL:
//                        break;
//                }
//            }
//        };
//        // dialog参数设置
//        AlertDialog.Builder builder = new AlertDialog.Builder(this); // 先得到构造器
//        builder.setTitle(R.string.HZKLdevices_config_dialog_title); // 设置标题
//        builder.setMessage(R.string.HZKLdevices_config_dialog_message); // 设置内容
//        builder.setPositiveButton(R.string.HZKLdialog_positive,
//                dialogOnclicListener);
//        builder.setNegativeButton(R.string.HZKLdialog_nagative,
//                dialogOnclicListener);
//        builder.create().show();
//    }


    /**
     * 请求相关权限
     */
    private void requestLocationPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            Log.d("Uriah", "Uriah + shouldShowRequestPermission true");
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    1);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    1);
        }
    }

    /**
     * 请求相关权限
     */
    private void requestCameraPermission() {

        boolean isMinSDKM = Build.VERSION.SDK_INT < 23;
        boolean isGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
        if (isMinSDKM || isGranted) {
            startActivityForResult(new Intent(CameraDeviceAddActivity.this, CaptureActivity.class), 0x11111);
            return;
        }
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            Log.d("Uriah", "Uriah + shouldShowRequestPermission true");
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    2);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    2);
        }
    }

    /**
     * 请求存储权限
     *
     */
//    private void requestStoragePermission(){
//        boolean isMinSDKM = Build.VERSION.SDK_INT < 23;
//        boolean isGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
//        if (isMinSDKM || isGranted) {
////            checkOnBindAndRemind();
//            showWifiConfig();
//            // 存储权限
//            return;
//        }
//        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//
//            Log.d("Uriah", "Uriah + shouldShowRequestPermission true");
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
//        } else {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
//        }
//
//    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        // TODO Auto-generated method stub
//        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            if (requestCode == 1) {
////                showPairDescription();
//                startConfig();
//            } else if (requestCode == 2) {
//                startActivityForResult(new Intent(CameraDeviceAddActivity.this, CaptureActivity.class), 0x11111);
//            }else if(requestCode == 3){
////                checkOnBindAndRemind();
//                showWifiConfig();
//            }
//
//        } else {
//            if (requestCode == 1) {
//                toast(getString(R.string.HZKLtoast_permission_location_forbidden));
//            } else if (requestCode == 2) {
//                toast(getString(R.string.HZKLtoast_permission_camera_forbidden));
//            } else if(requestCode == 3){
//                toast(getString(R.string.HZKLtoast_permission_storage_forbidden));
//            }
//
//        }
//
//    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 0x11111 && resultCode == RESULT_OK) {
//            Bundle bundle = data.getExtras();
//            String result = bundle.getString("result");
//            String devSn="";
//            if (result.contains(",")) {
//                devSn = result.split(",")[0].split(":")[1];
//            }else if(result.contains(":")){
//                devSn=result.split(":")[0];
//                devType=result.split(":")[1];
//            }
//            if(devSn!=null&&devSn.length()!=15){
//                devSn= result.substring(result.indexOf(":")+1,result.indexOf("}"));
//            }
//            binding.edSn.setText(devSn);
//        } else if (requestCode == 10000 && resultCode == RESULT_OK) {
//            finish();
//        }
//    }

    /**
     * 启动无线配对
     */
    private void startConfig() {
        // 开启播放加载控件
//        binding.tvIntro.setText("正在连接路由器，请稍候...");
        binding.queryLoad.setStart("正在连接路由器，请稍候...") ;//开始智能配置...//无线配网搜索设备中...
//        binding.probar.setVisibility(View.VISIBLE);
//        String ssid = mWifiInfo.getSSID().replaceAll("\"", "");
//        String ssid_pwd = binding.edWifiPsw.getText().toString();
//        String code = binding.edSn.getText().toString().toUpperCase();

        startCount(120);
        String ssid = getIntent().getStringExtra("ssid");
        String ssid_pwd = getIntent().getStringExtra("ssidPwd");
        String code = getIntent().getStringExtra("sn");
        String mCapabilities = getWifiCapabilities(ssid);
        // 无线超时任务
        mHandler.postDelayed(progressRun, CONFIG_WIFI_TIMEOUT_TIME);
        // 调用接口，开始通过smartConfig匹配 (频率由11000-->17000)
        Log.i("TAG","configWifiStart");
        LCOpenSDK_ConfigWifi.configWifiStart(code, ssid, ssid_pwd, "", LCSmartConfig.ConfigType.LCConfigWifi_Type_ALL,true,11000,1);
        searchDevice(CONFIG_SEARCH_DEVICE_TIME);//搜索设备及超时时间
    }

    private void startCount(int s){
        binding.customPro.setCountdownTime(s);
        binding.customPro.startCountdown(new CalProgressView.OnCountDownFinishListener() {
            @Override
            public void countDownFinished() {
//                customPro.setVisibility(View.GONE);
               // toast("连接超时");

//                finish();
                binding.customPro.setVisibility(View.GONE);
                binding.queryLoad.setVisibility(View.GONE);
                binding.layoutRetry.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 关闭无线配对
     */
    private void stopConfig() {
        mHandler.removeCallbacks(progressRun);
        LCOpenSDK_ConfigWifi.configWifiStop();// 调用smartConfig停止接口
        Business.getInstance().stopSearchDevice();
    }

    /**
     * 获取wifi加密信息
     */
    private String getWifiCapabilities(String ssid) {
        String mCapabilities = null;
        ScanResult mScanResult = null;
        WifiManager mWifiManager = (WifiManager) getApplicationContext().getSystemService(Activity.WIFI_SERVICE);
        if (mWifiManager != null) {
            WifiInfo mWifi = mWifiManager.getConnectionInfo();
            if (mWifi != null) {
                // 判断SSID是否�?��
                if (mWifi.getSSID() != null
                        && mWifi.getSSID().replaceAll("\"", "").equals(ssid)) {
                    List<ScanResult> mList = mWifiManager.getScanResults();
                    if (mList != null) {
                        for (ScanResult s : mList) {
                            if (s.SSID.replaceAll("\"", "").equals(ssid)) {
                                mScanResult = s;
                                break;
                            }
                        }
                    }
                }
            }
        }
        mCapabilities = mScanResult != null ? mScanResult.capabilities : null;
        return mCapabilities;
    }


    private void searchDevice(int timeout) {
        Log.i("TAG","searchDevice-" + getIntent().getStringExtra("sn"));
        final String deviceId = getIntent().getStringExtra("sn");
        Business.getInstance().searchDevice(deviceId, timeout, new Handler() {
            public void handleMessage(final Message msg) {
                Log.i("TAG","searchDevice-" + msg.what);
                if (msg.what < 0) {
                    if (msg.what == -2)
                        mHandler.obtainMessage(DEVICE_SEARCH_FAILED, "device not found").sendToTarget();
                    else
                        mHandler.obtainMessage(DEVICE_SEARCH_FAILED, "StartSearchDevices failed").sendToTarget();
                    return;
                }

                mHandler.obtainMessage(DEVICE_SEARCH_SUCCESS, msg.obj).sendToTarget();
            }
        });
    }

    private Runnable progressRun = new Runnable() {
        @Override
        public void run() {
            toast(getResources().getString(R.string.HZKLtoast_adddevice_config_timeout));
            stopConfig();
        }
    };

    private  void  showTipDialog(String tip){

        AlertDialog dialog = new AlertDialog.Builder(this).setTitle(tip).setNeutralButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                binding.customPro.setVisibility(View.GONE);
                binding.queryLoad.setVisibility(View.GONE);
                binding.layoutRetry.setVisibility(View.VISIBLE);
//                finish();
            }
        }).show();
    }


}
